<template>
  <Navbar />
  <div class="chat-container">
    <div class="chat-sidebar">
      <div class="search-bar">
        <input type="text" v-model="searchQuery" placeholder="搜索好友..." @input="searchFriends" />
      </div>
      <div class="friends-list">
        <div
          v-for="friend in filteredFriends"
          :key="friend.friend_user_id"
          class="friend-item" :class="{ 'active': chatStore.selectedFriend?.friend_user_id === friend.friend_user_id }"
          @click="selectFriend(friend)"
        >
          <img :src="getAvatarUrl(friend.avatar_url)" alt="Avatar" class="avatar" />
          <div class="friend-info">
            <div class="friend-name">{{ friend.username }}</div>
            <div class="status-indicator" :class="{ 'online': friend.login === 1 }">
              {{ friend.login === 1 ? '在线' : '离线' }}
            </div>
          </div>
          <div v-if="friend.unreadCount > 0" class="unread-count">{{ friend.unreadCount }}</div>
        </div>
      </div>
    </div>
    <div class="chat-main" v-if="chatStore.selectedFriend">
      <div class="chat-header">
        <img :src="getAvatarUrl(chatStore.selectedFriend.avatar_url)" alt="Avatar" class="avatar" />
        <div class="friend-info">
          <div class="friend-name">{{ chatStore.selectedFriend.username }}</div>
          <div class="status-indicator" :class="{ 'online': chatStore.selectedFriend.login === 1 }">
            {{ chatStore.selectedFriend.login === 1 ? '在线' : '离线' }}
          </div>
        </div>
      </div>
      <div class="chat-messages" ref="messagesContainer">
        <div
  v-for="message in chatStore.messages"
  :key="message.message_id"
  class="message" :class="{ 'sent': message.sender_id === chatStore.currentUserId, 'received': message.sender_id !== chatStore.currentUserId }"
  :title="`消息ID: ${message.message_id}, 发送者ID: ${message.sender_id}, 当前用户ID: ${chatStore.currentUserId}`"
>
  {{ console.log(`[${new Date().toLocaleString()}] [DEBUG] 消息ID: ${message.message_id}, 发送者ID: ${message.sender_id}, 当前用户ID: ${chatStore.currentUserId}, 应用样式: ${message.sender_id === chatStore.currentUserId ? 'sent' : 'received'}`) }}
          <div class="message-content">{{ message.content }}</div>
          <div class="message-time">{{ formatTime(message.created_at) }}</div>
          <div v-if="message.is_read && message.receiver_id === chatStore.currentUserId" class="read-indicator">已读</div>
        </div>
      </div>
      <div class="chat-input">
        <input
          type="text"
          v-model="messageInput"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
        />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
    <div class="chat-placeholder" v-else>
      请选择一个好友开始聊天
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed } from 'vue';
import Navbar from '../components/Navbar.vue';
import { useChatStore } from '../store/chat';
import type { Friend } from '../store/chat';

// 全局常量和状态
const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000';
const defaultAvatar = 'https://via.placeholder.com/40';

// 统一的头像URL拼接方法（与Navbar.vue保持一致）
const getAvatarUrl = (avatar: string | null) => {
  if (!avatar) return defaultAvatar;
  if (avatar.startsWith('http') || avatar.startsWith('data:')) return avatar;
  if (avatar.startsWith('/uploads/')) return API_BASE + avatar;
  return defaultAvatar;
};
const messageInput = ref('');
const searchQuery = ref('');
const messagesContainer = ref<HTMLDivElement | null>(null);

// 使用Pinia store
const chatStore = useChatStore();

// 计算属性
const filteredFriends = computed<Friend[]>(() => {
  if (!searchQuery.value) {
    return chatStore.friends;
  }

  const query = searchQuery.value.toLowerCase();
  return chatStore.friends.filter((friend: Friend)=>
    friend.username.toLowerCase().includes(query)
  );
});

// 初始化
onMounted(async () => {
  await chatStore.initialize();
  console.log(`[${new Date().toLocaleString()}] [INFO] 聊天组件已初始化`);
  // 调试头像URL
  console.log(`[${new Date().toLocaleString()}] [DEBUG] 好友列表:`, chatStore.friends);
  chatStore.friends.forEach(friend => {
    console.log(`[${new Date().toLocaleString()}] [DEBUG] 好友 ${friend.username} 的头像URL:`, friend.avatar_url);
  });
});

onUnmounted(() => {
  chatStore.cleanup();
});

// 搜索好友
const searchFriends = () => {
  // 由computed属性自动处理
};

// 选择好友
const selectFriend = async (friend: Friend) => {
  await chatStore.selectFriend(friend);
  messageInput.value = '';
  scrollToBottom();
};

// 发送消息
const sendMessage = async () => {
  if (!chatStore.selectedFriend || !messageInput.value.trim()) {
    return;
  }

  try {
    const content = messageInput.value.trim();
    await chatStore.sendMessage(chatStore.selectedFriend.friend_user_id, content);
    messageInput.value = '';
    scrollToBottom();
  } catch (error) {
    // 错误处理已在store中完成
  }
};

// 格式化时间
const formatTime = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  }, 100);
};

// 监听消息列表变化，自动滚动到底部
watch(
  () => chatStore.messages,
  () => {
    scrollToBottom();
  }
);

// 监听选中好友变化，自动滚动到底部
watch(
  () => chatStore.selectedFriend,
  () => {
    scrollToBottom();
  }
);
</script>

<style scoped>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  overflow: hidden;
}
.chat-container {
  display: flex;
  height: calc(100vh - 70px); /* 减去导航栏高度，避免页面滚动 */
  width: 100%;
  margin-top: 70px; /* 为导航栏腾出空间，导航栏高度为70px */
  overflow: hidden; /* 防止容器内容溢出导致滚动 */
}

.chat-sidebar {
  width: 300px;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
}

.search-bar {
  padding: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.search-bar input {
  width: 100%;
  padding: 8px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.friends-list {
  flex: 1;
  overflow-y: auto;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.friend-item:hover {
  background-color: #f5f5f5;
}

.friend-item.active {
  background-color: #e3f2fd;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.friend-info {
  flex: 1;
}

.friend-name {
  font-weight: 500;
  margin-bottom: 2px;
}

.status-indicator {
  font-size: 12px;
  color: #666;
}

.status-indicator.online {
  color: #4caf50;
}

.unread-count {
  background-color: #f44336;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 10px 15px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
}

.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.message {
  margin-bottom: 15px;
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.message.sent {
  margin-left: auto;
  align-items: flex-end;
}

.message.received {
  margin-right: auto;
  align-items: flex-start;
}

.message-content {
  padding: 10px 15px;
  border-radius: 18px;
  word-break: break-word;
}

.message.sent .message-content {
  background-color: #bbdefb;
  color: #0d47a1;
  border: 1px solid #90caf9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.message.received .message-content {
  background-color: white;
  border: 1px solid #e0e0e0;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.read-indicator {
  font-size: 12px;
  color: #2196f3;
  margin-top: 2px;
}

.chat-input {
  padding: 10px 15px;
  border-top: 1px solid #e0e0e0;
  display: flex;
}

.chat-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  margin-right: 10px;
}

.chat-input button {
  padding: 10px 20px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.chat-input button:hover {
  background-color: #1976d2;
}

.chat-placeholder {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 18px;
}
</style>